<template>
  <el-dialog v-if="formOpen" :title="title" :visible.sync="formOpen" :width="dialogWidth" :close-on-click-modal="false" @close="cancel">
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-row>
        <template v-if="fromProject">
          <el-col :span="24">
            <el-divider content-position="left">项目信息</el-divider>
          </el-col>
          <el-col :span="24" :xs="24" :sm="18">
            <el-form-item label="需求项目" prop="deptId">
              <treeselect
                v-model="formData.projectId"
                :options="projOptions"
                placeholder="请选择项目"
              />
            </el-form-item>
          </el-col>
        </template>
        <el-col :span="24">
          <el-divider content-position="left">基本信息</el-divider>
        </el-col>
        <el-col :span="24" :xs="24" :sm="12">
          <el-form-item label="姓名" prop="name" style="letter-spacing:0.33em;"><el-input
            v-model="formData.name"
            placeholder="请输入姓名"
            clearable
            prefix-icon="el-icon-user-solid"
            size="small"
          />
          </el-form-item>
        </el-col>
        <el-col :span="24" :xs="24" :sm="12">
          <el-form-item label="手机号" prop="phone"><el-input
            v-model="formData.phone"
            placeholder="请输入手机号"
            prefix-icon="el-icon-phone"
            clearable
            size="small"
          />
          </el-form-item>
        </el-col>
        <el-col :span="24" :xs="24" :sm="12">
          <el-form-item label="性别" prop="sex"><el-select
            v-model="formData.sex"
            placeholder="性别"
            clearable
            size="small"
          >
            <el-option
              v-for="dict in sexOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24" :xs="24" :sm="12">
          <el-form-item label="评级" prop="level"><el-input
            v-model="formData.level"
            placeholder="请输入评级"
            prefix-icon="el-icon-trophy-1"
            clearable
            size="small"
          />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-divider content-position="left">教育经历</el-divider>
        </el-col>
        <el-col :span="24" :xs="24" :sm="12">
          <el-form-item label="学校" prop="school">
            <el-input
              v-model="formData.school"
              placeholder="请输入学校"
              clearable
              prefix-icon="el-icon-school"
              :style="{width: '100%'}"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24" :xs="24" :sm="12">
          <el-form-item label="时间" prop="schoolTime">
            <el-date-picker
              v-model="formData.schoolTime"
              type="daterange"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              :style="{width: '100%'}"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              range-separator="至"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-divider content-position="left">工作经历</el-divider>
        </el-col>
        <el-col :span="24" :xs="24" :sm="12">
          <el-form-item label="公司" prop="company">
            <el-input
              v-model="formData.company"
              placeholder="请输入公司"
              clearable
              prefix-icon="el-icon-office-building"
              :style="{width: '100%'}"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24" :xs="24" :sm="12">
          <el-form-item label="时间" prop="companyTime">
            <el-date-picker
              v-model="formData.companyTime"
              type="daterange"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              :style="{width: '100%'}"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              range-separator="至"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-divider content-position="left">备注信息</el-divider>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="note">
            <el-input
              v-model="formData.note"
              type="textarea"
              placeholder="请输入备注信息"
              clearable
              size="small"
              :autosize="{minRows: 4, maxRows: 10}"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row v-if="!isNew">
      <el-col :span="24">
        <el-divider content-position="left">简历列表</el-divider>
      </el-col>
      <el-col :span="24">
        <el-upload
          action="#"
          list-type="picture-card"
          :file-list="formData.resumeList"
          :on-success="handleResumeSuccess"
          :on-error="handleResumeError"
          multiple
          :headers="upload.headers"
          :auto-upload="resumeUpload.autoUpload"
          :http-request="handleResumeUpload"
        >
          <i slot="default" class="el-icon-plus" />
          <div slot="file" slot-scope="{file}">
            <img
              class="el-upload-list__item-thumbnail"
              :src="fileIcon(file)"
              alt=""
            >
            <span class="el-upload-list__item-actions">
              <span
                class="el-upload-list__item-preview"
                @click="handleResumePreview(file)"
              >
                <i class="el-icon-zoom-in" />
              </span>
              <!-- <span
                v-if="!resumeUpload.disabled"
                class="el-upload-list__item-delete"
                @click="handleResumeDownload(file)"
              >
                <i class="el-icon-download" />
              </span> -->
              <span
                v-if="!resumeUpload.disabled"
                class="el-upload-list__item-delete"
                @click="handleResumeRemove(file)"
              >
                <i class="el-icon-delete" />
              </span>
            </span>
            <div class="el-upload-list__item-name" style="margin: 0 5px; display: block; text-align: center;">
              {{ file.updatedAt.split('T')[0] }}
            </div>
          </div>
        </el-upload>
        <el-progress
          v-show="showProgress"
          :stroke-width="6"
          :percentage="progressPercent"
        />
        <el-dialog :visible.sync="resumeUpload.showResume" width="80%" :close-on-click-modal="false" append-to-body @close="cancelPreview">
          <vue-office-docx v-if="resumeUpload.resumeUri.endsWith('.docx')" :src="resumeUpload.resumeUri" />
          <vue-office-pdf v-else-if="resumeUpload.resumeUri.endsWith('.pdf')" :src="resumeUpload.resumeUri" />
          <div v-else>不支持预览</div>
        </el-dialog>
      </el-col>

    </el-row>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>

  <!-- 用户导入对话框 -->
  <el-dialog v-else-if="uploadOpen" :title="title" :visible.sync="uploadOpen" :width="dialogWidth" :close-on-click-modal="false" @close="cancel">

    <el-upload
      ref="upload"
      :limit="1"
      accept=".xlsx, .xls"
      :headers="upload.headers"
      :action="upload.url + '?updateSupport=' + upload.updateSupport + '&projectId=' + projectId"
      :disabled="upload.isUploading"
      :on-progress="handleFileUploadProgress"
      :on-success="handleFileSuccess"
      :file-list="upload.fileList"
      :auto-upload="false"
      drag
    >
      <i class="el-icon-upload" />

      <div class="el-upload__text">
        将文件拖到此处，或
        <em>点击上传</em>
      </div>
      <div slot="tip" class="el-upload__tip">
        <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
        <el-link type="info" :href="templateUrl" style="font-size:12px">下载模板</el-link>
      </div>
      <div slot="tip" class="el-upload__tip" style="color:red">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
    </el-upload>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitFileForm">确 定</el-button>
      <el-button @click="upload.open = false">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getToken } from '@/utils/auth'
import { addHtTalent, updateHtTalent, uploadResume } from '@/api/hunter/ht-talent'
import { delHtResume } from '@/api/hunter/ht-resume'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import VueOfficeDocx from '@vue-office/docx'
import VueOfficePdf from '@vue-office/pdf'
export default {
  name: 'TalentInfo',
  components: { Treeselect, VueOfficeDocx, VueOfficePdf },
  props: {
    form: {
      type: Object,
      default: null
    },
    projOptions: {
      type: Array,
      default: () => []
    },
    title: {
      type: String,
      default: ''
    },
    fromProject: {
      type: Boolean,
      default: false
    },
    formOpen: {
      type: Boolean,
      default: false
    },
    uploadOpen: {
      type: Boolean,
      default: false
    },
    onClose: {
      type: Function,
      required: true
    }
  },

  data() {
    return {
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      isNew: false,
      templateUrl: process.env.VUE_APP_BASE_API + '/static/importTalent.xlsx',
      statusOptions: [],
      sexOptions: [],
      // 用户导入参数
      upload: {
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/api/v1/ht-talent/importData'
      },
      resumeUpload: {
        disabled: false,
        autoUpload: true,
        // 是否禁用上传
        isUploading: false,
        showResume: false,
        resumeUri: '',
        showProgress: false,
        progressPercent: 0,
        resumeUrl: '',
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() }
      },
      formData: {
        name: undefined,
        phone: undefined,
        sex: undefined,
        level: undefined,
        school: undefined,
        schoolTime: ['2024-12-31', '2025-02-03'],
        company: undefined,
        companyTime: ['2024-12-31', '2025-02-03'],
        note: undefined,
        projectId: undefined,
        submit: undefined,
        resumeList: []
      },
      rules: {
        name: [{
          required: true,
          message: '请输入姓名',
          trigger: 'blur'
        }],
        phone: [{
          required: true,
          message: '请输入电话',
          trigger: 'blur'
        }],
        sex: [],
        level: [],
        // school: [{
        //   required: true,
        //   message: '请输入学校',
        //   trigger: 'blur'
        // }],
        // schoolTime: [{
        //   required: true,
        //   type: 'array',
        //   message: '请至少选择一个时间',
        //   trigger: 'change'
        // }],
        // company: [{
        //   required: true,
        //   message: '请输入公司',
        //   trigger: 'blur'
        // }],
        // companyTime: [{
        //   required: true,
        //   type: 'array',
        //   message: '请至少选择一个时间',
        //   trigger: 'change'
        // }],
        note: []
      }
    }
  },
  computed: {
    projectId() {
      if (this.fromProject) {
        return this.form.projectId
      } else {
        return this.formData.projectId
      }
    },
    dialogWidth() {
      return window.innerWidth <= 600 ? '90%' : '55%'
    }
  },
  watch: {},
  created() {
    this.getDicts('sys_normal_disable').then(response => {
      this.statusOptions = response.data
    })
    this.getDicts('sys_user_sex').then(response => {
      this.sexOptions = response.data
    })
    if (this.form) {
      this.formData = this.form
    }
    this.isNew = this.form.id === undefined
  },
  mounted() {},
  methods: {
    /** 提交按钮 */
    submitForm: function() {
      var that = this
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {
            updateHtTalent(this.form).then(response => {
              if (response.code === 200) {
                that.msgSuccess(response.msg)
                that.onClose()
              } else {
                that.msgError(response.msg)
              }
            })
          } else {
            addHtTalent(this.form).then(response => {
              if (response.code === 200) {
                that.msgSuccess(response.msg)
                that.onClose()
              } else {
                that.msgError(response.msg)
              }
            })
          }
        }
      })
    },
    resetForm() {
      this.$refs['form'].resetFields()
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert(response.msg, '导入结果', { dangerouslyUseHTMLString: true })
      this.onClose()
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },
    // 取消按钮
    cancel() {
      this.onClose()
    },
    cancelPreview() {
      this.resumeUpload.showResume = false
      this.resumeUpload.resumeUri = ''
    },

    // 简历预览
    handleResumePreview(file) {
      this.resumeUpload.resumeUri = process.env.VUE_APP_BASE_API + '/static/resume/' + file.fileUri
      this.resumeUpload.showResume = true
    },
    // 简历下载
    handleResumeDownload(file) {
      // this.resumeUrl = process.env.VUE_APP_BASE_API + '/static/resume/' + file.fileUri
      // this.download(this.resumeUrl)
    },
    // 简历删除
    handleResumeRemove(file) {
      var that = this
      this.$confirm('是否确认删除简历?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delHtResume({
          'ids': [file.id]
        }).then((response) => {
          if (response.code === 200) {
            that.msgSuccess(response.msg)
            // 从列表中删除
            that.formData.resumeList = that.formData.resumeList.filter(item => {
              return item.id !== file.id
            })
          } else {
            that.msgError(response.msg)
          }
        })
      }).catch(() => {})
    },
    fileIcon(file) {
      var pic = file.fileUri.split('.')[1].toLowerCase() // 获取文件扩展名
      return require(`@/assets/${pic}.jpeg`) // 使用 require 动态加载图片
    },
    handleResumeUpload(file) {
      const formData = new FormData()
      formData.append('id', this.formData.id)
      formData.append('upload[]', file.file)

      const that = this
      uploadResume(formData, { onUploadProgress: (event) => {
        that.resumeUpload.showProgress = true
        that.resumeUpload.progressPercent = Math.round(event.loaded / event.total * 100)
      } }).then(response => {
        if (response.code === 200) {
          that.resumeUpload.showProgress = false
          that.resumeUpload.progressPercent = 0
          that.formData.resumeList === undefined ? that.formData.resumeList = [] : undefined
          that.formData.resumeList = that.formData.resumeList.concat(response.data)
          that.msgSuccess(response.msg)
        } else {
          that.msgError(response.msg)
        }
      })
    }
  }
}
</script>
